<template>
  <div class="login-container">
    <!-- 左侧内容区域 -->
    <div class="left-content">
      <!-- 主标题区域 -->
      <div class="hero-section">
        <h1 class="main-title">
          <span class="title-primary">KiKi Ai</span>
        </h1>
        <p class="title-subtitle">小朋友们最好的AI学习伙伴，让学习更智能，让成长更精彩</p>
      </div>

      <!-- 功能介绍板块 -->
      <div class="features-section">
        <!-- 板块2：聚合顶尖模型 -->
        <div class="feature-block">
          <div class="feature-content">
            <h3 class="feature-title">一站式聚合全球顶尖AI学习大模型</h3>
            <p class="feature-description">
              为教学注入无限动力，为每个学习问题提供最佳解决方案
            </p>
            
            <!-- AI专家模型展示 -->
            <div class="ai-models-section">
              <div class="models-grid">
                <div class="model-card">
                  <div class="model-icon bg-blue-500">
                    <i class="fas fa-robot"></i>
                  </div>
                  <div class="model-info">
                    <h5 class="model-name">Gemini 2.5 Pro (博学的大学教授)</h5>
                    <p class="model-expertise">知识渊博，逻辑严密。适合深度学术探讨、复杂问题推理。</p>
                  </div>
                </div>
                
                <div class="model-card">
                  <div class="model-icon bg-purple-500">
                    <i class="fas fa-lightbulb"></i>
                  </div>
                  <div class="model-info">
                    <h5 class="model-name">GPT-4o (全能的常春藤导师)</h5>
                    <p class="model-expertise">反应迅捷，善于沟通。精通多模态对话，是你的全能日常助手。</p>
                  </div>
                </div>
                
                <div class="model-card">
                  <div class="model-icon bg-green-500">
                    <i class="fas fa-code"></i>
                  </div>
                  <div class="model-info">
                    <h5 class="model-name">Claude 3 Opus (富有创造力的文学家)</h5>
                    <p class="model-expertise">文笔优美，思想深刻。擅长长文写作、创意构思和伦理分析。</p>
                  </div>
                </div>
                
                <div class="model-card">
                  <div class="model-icon bg-orange-500">
                    <i class="fas fa-language"></i>
                  </div>
                  <div class="model-info">
                    <h5 class="model-name">DeepSeek-V3 (严谨的科研学者)</h5>
                    <p class="model-expertise">代码与逻辑大师。专注于编程、数学和需要精确推理的任务。</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 右侧登录区域 - 集成 Authing -->
    <div class="right-content">
      <!-- 当guard还未渲染时，显示骨架屏 -->
      <div v-if="!isGuardReady" class="w-full max-w-sm mx-auto animate-pulse">
        <div class="h-10 bg-gray-200 rounded w-1/3 mb-6"></div>
        <div class="h-12 bg-gray-200 rounded mb-4"></div>
        <div class="h-12 bg-gray-200 rounded mb-6"></div>
        <div class="h-12 bg-blue-200 rounded"></div>
      </div>
      <!-- Guard的真实挂载点，初始时隐藏 -->
      <div id="authing-guard-container" :style="{ visibility: isGuardReady ? 'visible' : 'hidden' }"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useGuard } from '@authing/guard-vue3'
import { ElMessage, ElLoading } from 'element-plus'
import type { AuthenticationClient } from "@authing/guard-vue3";
import request from '@/utils/request'


const router = useRouter()
const guard = useGuard()

// 状态管理
const showError = ref(false)
const isGuardReady = ref(false);

onMounted(async () => {
  try {
      // 监听'onLoad'事件，当Guard完全准备好时触发
    guard.on('load', () => {
      isGuardReady.value = true;
    });

    // 启动 Authing Guard 组件
    await guard.start('#authing-guard-container')
    
    // 监听登录成功事件
    guard.on('login', (userInfo) => {
      console.log('Authing 登录成功:', userInfo)
      handleAuthingLoginSuccess(userInfo)
    })
    
    // 监听登录失败事件
    guard.on('login-error', (error) => {
      console.error('Authing 登录失败:', error)
      ElMessage.error('登录失败，请重试')
    })
    
    // 监听注册成功事件
    guard.on('register', (userInfo) => {
      console.log('Authing 注册成功:', userInfo)
      handleAuthingLoginSuccess(userInfo)
    })
    
    
  } catch (error) {
    console.error('Authing Guard 启动失败:', error)
    showError.value = true
  }
})

// Authing 登录成功处理
const handleAuthingLoginSuccess = async (userInfo: any) => {
  try {
    // 1. 先保存token到本地存储
    localStorage.setItem('authingToken', userInfo.token)
    localStorage.setItem('userId', userInfo.id)
    
    try {
      // 2. 使用request.ts发送请求，会自动添加Authorization头
      const response = await request.get('/auth/verify')
      
      if (response.data.success) {
        // 3. 认证成功，保存完整用户信息
        localStorage.setItem('userInfo', JSON.stringify({
          id: response.data.user.id,
          username: response.data.user.username,
          email: response.data.user.email,
          nickname: response.data.user.nickname,
          avatar: response.data.user.picture,
          token: userInfo.token
        }))
        
        // 4. 关闭验证状态，显示成功消息
        ElMessage.success('登录成功')
        
        // 5. 延迟1秒后跳转，让用户看到成功消息
        router.push('/')
        
      } else {
        // 认证失败
        ElMessage.error('身份验证失败：' + response.data.message)
        localStorage.removeItem('authingToken')
      }
      
    } catch (error: any) {
      // 网络请求失败
      console.error('认证请求失败:', error)
      
      if (error.response?.status === 401) {
        ElMessage.error('身份验证失败，请重新登录')
      } else {
        ElMessage.error('网络错误，请稍后重试')
      }
      
      localStorage.removeItem('authingToken')
    }
    
  } catch (error) {
    console.error('登录处理失败:', error)
    ElMessage.error('登录失败，请重试')
  }
}

// 重试加载
const retryLoad = () => {
  showError.value = false
  isGuardReady.value = false
  // 重新挂载组件
  location.reload()
}

// 清理事件监听器
onUnmounted(() => {
  // Authing Guard 会自动清理事件监听器，无需手动清理
  // 或者使用 guard.destroy() 如果该方法存在
})

</script>

<style scoped>
/* 基础布局 */
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 50%, #f8fafc 100%);
  display: flex;
  overflow: hidden;
}

.left-content {
  width: 60%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 3rem 2.5rem;
  overflow-y: auto;
  min-height: 100vh;
  background-color: rgb(248 250 252 / var(--tw-bg-opacity, 1));
}

/* 修改右侧内容区域，让登录组件靠右 */
.right-content {
  width: 40%;
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 改为 flex-end */
  padding: 2rem 1rem 2rem 0; /* 右边距减少到1rem，左边距为0 */
  overflow-y: auto;
  position: relative; /* 添加相对定位 */
}

/* 或者如果你想要登录卡片本身靠右 */
.login-card {
  width: 100%;
  max-width: 26rem;
  background-color: white;
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  padding: 1.75rem;
  margin-left: auto; /* 添加这行让卡片靠右 */
}

/* Hero区域 - 居中排列 */
.hero-section {
  margin-bottom: 2rem;
  text-align: center;
}

.main-title {
  font-size: 3rem;
  font-weight: 700;
  margin-bottom: 0.75rem;
  line-height: 1.1;
}

.title-primary {
  background: rgb(79 70 229 / var(--tw-bg-opacity, 1));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  font-weight: bold;
  font-size: 4rem;
}

.title-subtitle {
  font-size: 1.125rem;
  color: #6b7280;
  font-weight: 400;
  margin: 0;
}

/* 功能介绍区域 */
.features-section {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.feature-block {
  display: flex;
  align-items: flex-start;
  gap: 1.25rem;
}

.feature-content {
  flex: 1;
  text-align: center;
}

.feature-title {
  font-size: 1.375rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 0.5rem 0;
  line-height: 1.3;
}

.feature-description {
  font-size: 0.9375rem;
  color: #4b5563;
  line-height: 1.5;
  margin: 0;
}

/* AI专家模型区域 */
.ai-models-section {
  margin-top: 1.25rem;
  max-width: 80%;
  margin-left: auto;
  margin-right: auto;
}

.models-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.25rem;
}

.model-card {
  background: white;
  padding: 1rem;
  border-radius: 0.5rem;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.model-card:hover {
  border-color: #4F46E5;
  transform: scale(1.05);
}

.model-icon {
  width: 3rem;
  height: 3rem;
  border-radius: 0.75rem;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.model-icon i {
  font-size: 1.25rem;
  color: white;
}

.model-info {
  flex: 1;
  text-align: left;
}

.model-name {
  font-size: 1.125rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 0.25rem 0;
  text-align: left;
}

.model-expertise {
  font-size: 0.875rem;
  color: #6b7280;
  margin: 0;
  line-height: 1.4;
  text-align: left;
}

/* 登录表单样式 */
.login-header {
  text-align: center;
  margin-bottom: 1.75rem;
}

.logo {
  font-family: 'Pacifico', cursive;
  font-size: 1.75rem;
  color: #3b82f6;
  margin-bottom: 0.5rem;
}

.login-title {
  font-size: 1.375rem;
  font-weight: 600;
  color: #1f2937;
}

.login-subtitle {
  color: #6b7280;
  margin-top: 0.5rem;
  font-size: 0.9375rem;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.25rem;
}

.input-wrapper {
  position: relative;
}

.input-icon {
  position: absolute;
  left: 0.75rem;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
  pointer-events: none;
}

.form-input {
  width: 100%;
  padding: 0.75rem 0.75rem 0.75rem 2.5rem;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
  font-size: 1rem;
  transition: all 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.verification-wrapper {
  display: flex;
  gap: 0.75rem;
}

.verification-button {
  padding: 0.75rem 1rem;
  background-color: rgb(79 70 229 / var(--tw-bg-opacity, 1));
  color: white;
  border: none;
  border-radius: 0.5rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  font-size: 0.875rem;
}

.verification-button:hover:not(:disabled) {
  background-color: rgb(79 70 229 / var(--tw-bg-opacity, 1));
}

.verification-button:disabled {
  background-color: #e5e7eb;
  cursor: not-allowed;
}

.agreement {
  font-size: 0.75rem;
  color: #6b7280;
  text-align: center;
}

.agreement-link {
  color: #3b82f6;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}

/* 登录按钮样式 */
.login-button {
  width: 100%;
  padding: 0.75rem 1rem;
  background: rgb(79 70 229 / var(--tw-bg-opacity, 1));
  color: white;
  border: none;
  border-radius: 0.5rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.login-button:hover:not(:disabled) {
  background: rgb(79 70 229 / var(--tw-bg-opacity, 1));
  transform: translateY(-1px);
  box-shadow: 0 8px 25px -5px rgba(0, 0, 0, 0.15);
}

.login-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.button-content {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.button-content i {
  margin-right: 0.5rem;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .left-content {
    width: 50%;
    padding: 2.5rem 2rem;
  }
  
  .right-content {
    width: 50%;
    padding: 1.5rem;
  }
  
  .main-title {
    font-size: 2.5rem;
  }
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    overflow-y: auto;
  }
  
  .left-content {
    width: 100%;
    min-height: auto;
    padding: 1.5rem 1rem;
    flex: 0 0 auto;
  }
  
  .right-content {
    width: 100%;
    min-height: auto;
    padding: 1.5rem 1rem;
    flex: 0 0 auto;
  }
  
  .main-title {
    font-size: 2rem;
  }
  
  .title-subtitle {
    font-size: 1rem;
  }
  
  .feature-block {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .feature-title {
    font-size: 1.25rem;
  }
  
  .feature-description {
    font-size: 0.875rem;
  }
  
  .models-grid {
    grid-template-columns: 1fr;
    gap: 0.875rem;
  }
  
  .model-card {
    padding: 1rem;
  }
  
  .login-card {
    padding: 1.5rem;
  }
}

@media (max-width: 480px) {
  .left-content {
    padding: 1rem 0.75rem;
  }
  
  .right-content {
    padding: 1rem 0.75rem;
  }
  
  .main-title {
    font-size: 1.75rem;
  }
  
  .feature-title {
    font-size: 1.125rem;
  }
  
  .feature-description {
    font-size: 0.8125rem;
  }
  
  .model-card {
    padding: 0.875rem;
  }
  
  .login-card {
    padding: 1.25rem;
  }
  
  .verification-button {
    padding: 0.75rem 0.75rem;
    font-size: 0.8125rem;
  }
}

@media (max-width: 360px) {
  .left-content {
    padding: 0.75rem 0.5rem;
  }
  
  .right-content {
    padding: 0.75rem 0.5rem;
  }
  
  .main-title {
    font-size: 1.5rem;
  }
  
  .models-grid {
    gap: 0.75rem;
  }
  
  .login-card {
    padding: 1rem;
  }
}

/* 新增样式 */
.loading-container, .error-container {
  text-align: center;
  padding: 2rem;
  color: #6b7280;
}

.loading-container i, .error-container i {
  font-size: 2rem;
  margin-bottom: 1rem;
  display: block;
}

.retry-button {
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 0.375rem;
  cursor: pointer;
}

.retry-button:hover {
  background-color: #4338ca;
}

/* 隐藏 Authing 的加载动画 */
.authing-loading,
.authing-loading-overlay,
.g2-loading,
.authing-g2-loading,
.authing-g2-loading-overlay {
  display: none !important;
}

/* 隐藏加载相关的元素 */
[class*="loading"],
[class*="spinner"],
.authing-spinner {
  display: none !important;
}

/* 确保登录组件正常显示 */
.authing-g2-render-module-normal {
  position: fixed !important;
  left: 75% !important;
  top: 50% !important;
  transform: translate(-50%, -50%) !important;
}

.verification-content {
  text-align: center;
  padding: 2rem;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e5e7eb;
  border-top: 4px solid #4f46e5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

.verification-text {
  color: #4b5563;
  font-size: 1rem;
  font-weight: 500;
  margin: 0;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

</style>

<!-- 添加全局样式来完全覆盖 Authing 内部样式 -->
<style>
.g2-init-setting-loading {
  display: none !important;
  visibility: hidden !important;
} 

.g2-init-setting-loading {
  position: fixed !important;
  left: 75% !important;
  top: 50% !important;
  transform: translate(-50%, -50%) !important;
}

</style>
